<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      /*
      思路：两块石头相撞，所以求和一半为背包容量。
      每块石头都取一次，判断装满背包时的最大重量。然后用总和-2倍即可
      */
      var lastStoneWeightII = function (stones) {
        stones.sort((a, b) => a - b);
        let sum = stones.reduce((pre, item) => (pre += item));
        let bagSize = parseInt(sum / 2);
        let dp = new Array(bagSize + 1).fill(0);
        for (let i = 0; i < stones.length; i++) {
          for (let j = bagSize; j >= stones[i]; j--) {
            dp[j] = Math.max(dp[j], dp[j - stones[i]] + stones[i]);
          }
        }
        return sum - 2 * dp[bagSize];
      };
    </script>
  </body>
</html>
